package com.eee.common.util;

import java.security.MessageDigest;

import org.springframework.stereotype.Component;

/**
 * 所有的加密工具
 * 
 * @author eee
 *
 */

@Component("encryptUtil")
public class EncryptUtil
{

	private RegexUtil regexUtil = new RegexUtil();

	public String md5(String s)
	{
		char hexDigits[] =
		{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		try
		{
			byte[] btInput = s.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++)
			{
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 密码字符串
	 * 生成后的加密字符串永远不一样
	 * @param password
	 * @return
	 */
	public String encryString(String password)
	{
		String randStr = this.regexUtil.randString(32);
		System.out.println("生成的32位随机数---->"+randStr);
		String md5Str = randStr + "$MD5$";
		System.out.println("加上MD5后---->"+md5Str);
		/* 32位随机数+"$MD5$" MD5加密:(32位随机数$MD5$111111)*/
		randStr = this.md5(md5Str+password);
		return md5Str+randStr;
	}

	public boolean checkPassword(String password,String encStr)
	{
		if(encStr.indexOf("$") == -1)
		{
			return false;
		}
		String[] encStrs = encStr.split("\\$");
		String md5Str = encStrs[0]+"$"+encStrs[1]+"$"+password;
		md5Str = encStrs[0]+"$"+encStrs[1]+"$"+this.md5(md5Str);
		return md5Str.equalsIgnoreCase(encStr);
	}
	public static void main(String[] args)
	{
		EncryptUtil eu = new EncryptUtil();
		System.out.print(eu.md5("111111"));
		System.out.println(eu.encryString("111111"));
		String souStr = "LyK1rWHGQdMJwQPe75ygoCQjw9zdA6oi$MD5$834D54C73D5F98BDD5701576F4C12825";
		String pass = "111111";
		System.out.println(eu.checkPassword(pass, souStr));
		//MvjmqQBZzvc8xaFz3n5UZ4Yreksg5nuf$MD5$9875C98DD18A9E2F927AE6A7F61AD4FC
		//LyK1rWHGQdMJwQPe75ygoCQjw9zdA6oi$MD5$834D54C73D5F98BDD5701576F4C12825
	}
}
